<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="学习标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入学习标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:partyStudy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:partyStudy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:partyStudy:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:partyStudy:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" prop="title" min-width="180" show-overflow-tooltip />
      <el-table-column label="摘要" prop="description" min-width="200" show-overflow-tooltip />
      <el-table-column label="封面" width="120" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.coverImage"
            :src="getImageUrl(scope.row.coverImage)"
            style="width: 80px; height: 80px;"
            :preview-src-list="[getImageUrl(scope.row.coverImage)]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
              <div>加载失败</div>
            </div>
          </el-image>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="文件" prop="fileName" min-width="160">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.fileUrl"
            :href="getFileUrl(scope.row.fileUrl)"
            type="primary"
            target="_blank"
          >{{ scope.row.fileName || '下载资料' }}</el-link>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sortOrder" width="80" align="center" />
      <el-table-column label="发布时间" prop="publishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:partyStudy:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:partyStudy:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学习标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入学习标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="学习摘要" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入学习摘要" rows="3" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序值" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" :max="9999" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资料文件" prop="fileUrl">
          <file-upload v-model="form.fileUrl" :limit="1" :file-size="20" :is-show-tip="false" />
          <el-input
            v-model="form.fileUrl"
            placeholder="或直接粘贴文件访问地址"
            style="margin-top: 10px;"
            clearable
          />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <image-upload v-model="form.coverImage" :limit="1" :file-size="5" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="form.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            default-time="12:00:00"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容" rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="学习资料详情" :visible.sync="viewOpen" width="700px" append-to-body>
      <div v-if="viewData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题">{{ viewData.title }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <dict-tag :options="dict.type.sys_normal_disable" :value="viewData.status"/>
          </el-descriptions-item>
          <el-descriptions-item label="摘要" :span="2">{{ viewData.description || '—' }}</el-descriptions-item>
          <el-descriptions-item label="封面" :span="2">
            <el-image
              v-if="viewData.coverImage"
              :src="getImageUrl(viewData.coverImage)"
              style="width: 120px; height: 120px;"
              :preview-src-list="[getImageUrl(viewData.coverImage)]"
            />
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="资料文件" :span="2">
            <el-link
              v-if="viewData.fileUrl"
              :href="getFileUrl(viewData.fileUrl)"
              target="_blank"
            >{{ viewData.fileName || '下载资料' }}</el-link>
            <span v-else>—</span>
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ viewData.sortOrder }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">
            {{ parseTime(viewData.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ viewData.remark || '—' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPartyStudy, getPartyStudy, addPartyStudy, updatePartyStudy, delPartyStudy } from "@/api/system/partyStudy";

export default {
  name: "PartyStudy",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      resourceList: [],
      title: "",
      open: false,
      viewOpen: false,
      viewData: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        status: null
      },
      form: {},
      rules: {
        title: [
          { required: true, message: "学习标题不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        fileUrl: [
          { required: true, message: "请上传或填写资料文件", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listPartyStudy(this.queryParams).then(response => {
        this.resourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增学习资料";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPartyStudy(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑学习资料";
      });
    },
    handleView(row) {
      this.viewData = row;
      this.viewOpen = true;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePartyStudy(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPartyStudy(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的学习资料？').then(function () {
        return delPartyStudy(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('/api/party-study/export', {
        ...this.queryParams
      }, `party-study_${new Date().getTime()}.xlsx`);
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        title: null,
        description: null,
        fileName: null,
        fileUrl: null,
        coverImage: null,
        status: "0",
        sortOrder: 0,
        publishTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    getImageUrl(image) {
      if (!image) return "";
      if (image.startsWith('http') || image.startsWith('//')) {
        return image;
      }
      return process.env.VUE_APP_BASE_API + image;
    },
    getFileUrl(fileUrl) {
      if (!fileUrl) return "";
      if (fileUrl.startsWith('http') || fileUrl.startsWith('//')) {
        return fileUrl;
      }
      return process.env.VUE_APP_BASE_API + fileUrl;
    }
  }
}
</script>

<style scoped>
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-slot i {
  font-size: 30px;
  margin-bottom: 8px;
}
</style>

